package com.nearby.demand.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.auto.layout.lib.AutoLayoutActivity;
import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.facebook.drawee.view.SimpleDraweeView;
import com.nearby.demand.R;
import com.nearby.demand.adapter.ConversationsAdapter;
import com.nearby.demand.fragment.FragmentMine;
import com.nearby.demand.fragment.FragmentR;
import com.nearby.demand.fragment.FragmentRelease;
import com.nearby.demand.fragment.FragmentWorld;
import com.nearby.demand.fragment.Fragmentsanz;
import com.nearby.demand.ui.view.spinner.NiceSpinner;
import com.nearby.demand.utils.KLog;
import com.nearby.demand.utils.SPUtil;
import com.nearby.demand.widget.FABToolbarLayout;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * Created by Administrator on 2016/home_1/8.
 */
public class UiMain2 extends AutoLayoutActivity implements EMEventListener, View.OnClickListener {
    TextView unreaMsgdLabel;
    TextView unreadAddressLable;
    TextView unreadFindLable;
    public FragmentWorld homefragmentWorld;
    public FragmentRelease homefragmentRelease;
    public Fragmentsanz fragmentsanz;

    public FragmentMine homefragmentMine;
    public FragmentR homefragmentR;


    private Fragment[] fragments;
    private ImageView[] imagebuttons;
    private TextView[] textviews;
    //记录Fragment的位置
    private int position = 0;
    //    @TargetApi(19)
    //    private void setTranslucentStatus(boolean on) {
    //        Window win = getWindow();
    //        WindowManager.LayoutParams winParams = win.getAttributes();
    //        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
    //        if (on) {
    //            winParams.flags |= bits;
    //        } else {
    //            winParams.flags &= ~bits;
    //        }
    //        win.setAttributes(winParams);
    //    }

    RecyclerView recycler_views;
    PtrClassicFrameLayout mPtrFrames;

    DrawerLayout mDrawerLayout;

    NavigationView navigationView;
    NavigationView navigationViews;

    private void setupDrawerContentLeft(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {
                        menuItem.setChecked(true);
                        mDrawerLayout.closeDrawers();

                        switch (menuItem.getItemId()) {
                            case R.id.setting:
                                startActivity(new Intent(UiMain2.this, UiSetting.class));
                                break;
                            case R.id.help:
                                break;
                        }

                        return true;
                    }
                });


    }

    private void setupDrawerContentRight(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {
                        menuItem.setChecked(true);
                        mDrawerLayout.closeDrawers();
                        return true;
                    }
                });
    }

    TextView tv_login_name;
    SimpleDraweeView iv_login_avatar;
    FABToolbarLayout layout;
    private View one, two, three, four;
    private View fab;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ui_main2);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationViews = (NavigationView) findViewById(R.id.nav_views);
//        View navigationHeaderView = navigationView.findViewById(R.id.nav_view);
        View headView = LayoutInflater.from(getApplicationContext()).inflate(R.layout
                .nav_header, null);
        navigationView.addHeaderView(headView);


        tv_login_name = (TextView) headView.findViewById(R.id.tv_login_name);
        iv_login_avatar = (SimpleDraweeView) headView.findViewById(R.id.iv_login_avatar);
        iv_login_avatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(UiMain2.this, UiLogin.class));
            }
        });

        //        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, navigationViews);
        if (navigationView != null) {
            setupDrawerContentLeft(navigationView);
        }
        if (navigationViews != null) {
            setupDrawerContentRight(navigationViews);
        }
        conversationsAdapter = new ConversationsAdapter(conversationList, this);
        initConversations();//加载会话列表

        //        initChatListener();

        //        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        //            setTranslucentStatus(true);
        //        }
//        initSpinner();
        //        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        //        tintManager.setStatusBarTintEnabled(true);
        //        tintManager.setStatusBarTintResource(R.color.status_bar_bg);
        initTabView();
        setTabSelection(position);
        layout = (FABToolbarLayout) findViewById(R.id.fabtoolbar);
//        one = findViewById(R.id.one);
//        two = findViewById(R.id.two);
//        three = findViewById(R.id.three);
//        four = findViewById(R.id.four);
        fab = findViewById(R.id.fabtoolbar_fab);


        String[] data = new String[30];
        for (int i = 0; i < 30; i++) {
            data[i] = "Test " + i;
        }

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layout.show();
            }
        });
        tv_login_name.setText(String.valueOf(SPUtil.get(UiMain2.this, "name", "未登录")));
    }

    @Override
    public void onBackPressed() {
        layout.hide();
    }

    @Override
    public void onClick(View v) {
        Toast.makeText(this, "Element clicked", Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //使用环信的第二种监听方式[回调监听事件注册]
        EMChatManager.getInstance().registerEventListener(this,
                new EMNotifierEvent.Event[]{
                        EMNotifierEvent.Event.EventNewMessage,
                        EMNotifierEvent.Event.EventOfflineMessage,
                        EMNotifierEvent.Event.EventConversationListChanged});
    }

    /**
     * 刷新
     */
    private void refreshUI() {

        runOnUiThread(new Runnable() {
            public void run() {
                // 刷新bottom bar消息未读数
                updateUnreadLabel();
                conversationsAdapter.addList(loadConversationsWithRecentChat());
                conversationsAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void onEvent(EMNotifierEvent event) {
        KLog.i("消息来了" + event.getEvent());
        switch (event.getEvent()) {
            case EventNewMessage: // 接收新消息
            {
                EMMessage message = (EMMessage) event.getData();
                refreshUI();
                break;
            }
            case EventDeliveryAck: {//接收已发送回执

                break;
            }

            case EventNewCMDMessage: {//接收透传消息

                break;
            }

            case EventReadAck: {//接收已读回执

                break;
            }

            case EventOfflineMessage: {//接收离线消息
                List<EMMessage> messages = (List<EMMessage>) event.getData();
                break;
            }

            case EventConversationListChanged: {//通知会话列表通知event注册（在某些特殊情况，SDK去删除会话的时候会收到回调监听）

                break;
            }

            default:
                break;
        }
    }

    /**
     * 获取所有会话
     *
     * @param
     * @return +
     */
    private List<EMConversation> loadConversationsWithRecentChat() {
        // 获取所有会话，包括陌生人
        Hashtable<String, EMConversation> conversations = EMChatManager
                .getInstance().getAllConversations();
        List<EMConversation> list = new ArrayList<EMConversation>();
        // 过滤掉messages seize为0的conversation
        for (EMConversation conversation : conversations.values()) {
            if (conversation.getAllMessages().size() != 0)
                list.add(conversation);
        }
        // 排序
        sortConversationByLastChatTime(list);
        KLog.i("list-size=" + list.size());
        return list;
    }

    /**
     * 根据最后一条消息的时间排序
     *
     * @param
     */
    private void sortConversationByLastChatTime(
            List<EMConversation> conversationList) {
        Collections.sort(conversationList, new Comparator<EMConversation>() {
            @Override
            public int compare(final EMConversation con1,
                               final EMConversation con2) {

                EMMessage con2LastMessage = con2.getLastMessage();
                EMMessage con1LastMessage = con1.getLastMessage();
                if (con2LastMessage.getMsgTime() == con1LastMessage
                        .getMsgTime()) {
                    return 0;
                } else if (con2LastMessage.getMsgTime() > con1LastMessage
                        .getMsgTime()) {
                    return 1;
                } else {
                    return -1;
                }
            }

        });
    }


    private List<EMConversation> conversationList = new ArrayList<EMConversation>();
    ConversationsAdapter conversationsAdapter;

    public void initConversations() {
        conversationList.addAll(loadConversationsWithRecentChat());
        if (conversationList != null && conversationList.size() > 0) {
            //            layout.findViewById(R.id.txt_nochat).setVisibility(View.GONE);
            conversationsAdapter.notifyDataSetChanged();
        } else {
            //            layout.findViewById(R.id.txt_nochat).setVisibility(View.VISIBLE);
        }
    }

    public void initSpinner() {
        NiceSpinner niceSpinner = (NiceSpinner) findViewById(R.id.nice_spinner);
        List<String> data_set = new LinkedList<>(Arrays.asList("最近", "最新", "最热"));
        niceSpinner.attachDataSource(data_set);
    }

    public void hideFragments(FragmentTransaction transaction) {
        for (Fragment fragment : fragments) {
            transaction.hide(fragment);
        }
    }

    public void changeButtonStatus(int position) {
        for (int i = 0; i < imagebuttons.length; i++) {
            imagebuttons[i].setSelected(false);

        }
        for (int i = 0; i < textviews.length; i++) {
            textviews[i].setTextColor(0xFFFFFFFF);
        }
    }

    private void setTabSelection(int position) {
        //记录position
        this.position = position;
        //更改底部导航栏按钮状态
        changeButtonStatus(position);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        // 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
        hideFragments(transaction);
        switch (position) {
            case 0:
                imagebuttons[position].setSelected(true);
                textviews[position].setTextColor(0xFF6BB5E6);
                if (homefragmentWorld == null) {
                    homefragmentWorld = new FragmentWorld();
                    transaction.add(R.id.fragment_container, homefragmentWorld);
                } else {
                    transaction.show(homefragmentWorld);
                }
                break;
            case 1:
                imagebuttons[position].setSelected(true);
                textviews[position].setTextColor(0xFF6BB5E6);
                if (fragmentsanz == null) {
                    fragmentsanz = new Fragmentsanz();
                    transaction.add(R.id.fragment_container, fragmentsanz);
                } else {
                    transaction.show(fragmentsanz);
                }
                break;
            case 2:
                imagebuttons[position].setSelected(true);
                textviews[position].setTextColor(0xFF6BB5E6);
                if (homefragmentRelease == null) {
                    homefragmentRelease = new FragmentRelease();
                    transaction.add(R.id.fragment_container, homefragmentRelease);
                } else {
                    transaction.show(homefragmentRelease);
                }

                break;
            case 3:
                imagebuttons[position].setSelected(true);
                textviews[position].setTextColor(0xFF6BB5E6);
                if (homefragmentR == null) {
                    homefragmentR = new FragmentR();
                    transaction.add(R.id.fragment_container, homefragmentR);
                } else {
                    transaction.show(homefragmentR);
                }

                break;
            case 4:
                imagebuttons[position].setSelected(true);
                textviews[position].setTextColor(0xFF6BB5E6);
                if (homefragmentMine == null) {
                    homefragmentMine = new FragmentMine();
                    transaction.add(R.id.fragment_container, homefragmentMine);
                } else {
                    transaction.show(homefragmentMine);
                }

                break;
        }
        transaction.commitAllowingStateLoss();
    }

    public void initRight() {
        recycler_views = (RecyclerView) findViewById(R.id.recycler_view_s);

        mPtrFrames = (PtrClassicFrameLayout) findViewById(R.id.rotate_header_list_view_frames);
        mPtrFrames.setLastUpdateTimeRelateObject(this);
        mPtrFrames.setPtrHandler(new PtrDefaultHandler2() {

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                // TODO Auto-generated method stub
                mPtrFrames.refreshComplete();
            }

            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                // TODO Auto-generated method stub
                mPtrFrames.refreshComplete();
            }

        });
        // the following are default settings
        mPtrFrames.setResistance(1.7f);
        mPtrFrames.setRatioOfHeaderHeightToRefresh(1.2f);
        mPtrFrames.setDurationToClose(200);
        mPtrFrames.setDurationToCloseHeader(1000);
        // default is false
        mPtrFrames.setPullToRefresh(false);
        // default is true
        mPtrFrames.setKeepHeaderWhenRefresh(true);


        recycler_views.setHasFixedSize(true);//固定尺寸
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(UiMain2.this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycler_views.setLayoutManager(linearLayoutManager);
        //            recycler_view.addItemDecoration(new DividerItemDecoration(getActivity(),
        //                    DividerItemDecoration.VERTICAL_LIST));
        recycler_views.setAdapter(conversationsAdapter);
    }

    private void initTabView() {
        initRight();
        unreaMsgdLabel = (TextView) findViewById(R.id.unread_msg_number);//未读取消息
        homefragmentWorld = new FragmentWorld();
        fragmentsanz = new Fragmentsanz();
        homefragmentMine = new FragmentMine();
        homefragmentR = new FragmentR();
        homefragmentRelease = new FragmentRelease();

        fragments = new Fragment[]{homefragmentWorld, fragmentsanz,
                homefragmentMine, homefragmentR, homefragmentRelease};
        imagebuttons = new ImageView[5];
        imagebuttons[0] = (ImageView) findViewById(R.id.ib_world);
        imagebuttons[1] = (ImageView) findViewById(R.id.ib_author);
        imagebuttons[2] = (ImageView) findViewById(R.id.ib_release);
        imagebuttons[3] = (ImageView) findViewById(R.id.ib_message);
        imagebuttons[4] = (ImageView) findViewById(R.id.ib_home);


        imagebuttons[0].setSelected(true);
        textviews = new TextView[5];
        textviews[0] = (TextView) findViewById(R.id.tv_world);
        textviews[1] = (TextView) findViewById(R.id.tv_author);
        textviews[2] = (TextView) findViewById(R.id.tv_release);
        textviews[3] = (TextView) findViewById(R.id.tv_message);
        textviews[4] = (TextView) findViewById(R.id.tv_home);
        textviews[0].setTextColor(0xFF45C01A);
        // 添加显示第一个fragment
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, homefragmentWorld)
                .add(R.id.fragment_container, fragmentsanz)
                .add(R.id.fragment_container, homefragmentR)
                .add(R.id.fragment_container, homefragmentMine)
                .add(R.id.fragment_container, homefragmentRelease)
                .hide(fragmentsanz).hide(homefragmentR).hide(homefragmentMine).hide(homefragmentRelease)
                .show(homefragmentWorld).commitAllowingStateLoss();
        updateUnreadLabel();//自动更新未读信息
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        position = savedInstanceState.getInt("position");
        setTabSelection(position);
        super.onRestoreInstanceState(savedInstanceState);
    }


    public void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        //记录当前的position
        outState.putInt("position", position);
    }

    /**
     * 获取未读消息数
     */
    public void updateUnreadLabel() {
        int count = 0;
        count = EMChatManager.getInstance().getUnreadMsgsCount();
        if (count > 0) {
            unreaMsgdLabel.setText(String.valueOf(count));
            unreaMsgdLabel.setVisibility(View.VISIBLE);
        } else {
            unreaMsgdLabel.setVisibility(View.INVISIBLE);
        }
    }

    public void onTabClicked(View view) {
        switch (view.getId()) {
            case R.id.re_world:
                setTabSelection(0);
                layout.hide();
                break;
            case R.id.re_author:
                setTabSelection(1);

                break;
            case R.id.re_release:
                setTabSelection(2);

                break;
            case R.id.re_message:
                setTabSelection(3);

                break;
            case R.id.re_home:
                setTabSelection(4);

                break;
        }
    }

    private int keyBackClickCount = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            switch (keyBackClickCount++) {
                case 0:
                    Toast.makeText(this, "再次按返回键退出", Toast.LENGTH_SHORT).show();
                    Timer timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            keyBackClickCount = 0;
                        }
                    }, 3000);
                    break;
                case 1:
                    SPUtil.putAndApply(UiMain2.this, "is_login", false);
                    EMChatManager.getInstance().logout();
                    finish();
                    break;

            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
